<template>
  <div class="space-detail">
    <el-card class="search-card">
      <template #header>
        <h2 v-if="spaceName">{{ `${userStore.userInfo.userName} 的 ${spaceName} 空间` }}</h2>
      </template>
      <el-form :inline="true" :model="searchForm" @submit.prevent>
        <el-form-item label="图片名称">
          <el-input v-model="searchForm.searchQuery" placeholder="请输入图片关键字" clearable />
        </el-form-item>
        <el-form-item label="分类">
          <el-select
            v-model="searchForm.classifyId"
            placeholder="请选择图片分类"
            @change="onSearch"
          >
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="classify in classifyStore.classifies"
              :key="classify.id"
              :value="classify.id"
            >
              {{ classify.name }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="searchForm.date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="onSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="onReset">重置</el-button>
          <el-button type="success" @click="goToUpload"> 添加图片 </el-button>
          <el-button type="primary" icon="Edit" @click="goToBatchEdit">批量修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <div class="gallery-section">
      <div class="gallery-grid">
        {{ pictures.length === 0 ? '暂无图片' : '' }}
        <div v-for="item in pictures" :key="item.id" class="gallery-item">
          <div class="image-container" @click="goToCrop(item)">
            <img :src="item.thumbnailUrl || item.url" :alt="item.name" class="gallery-image" />
          </div>
          <h3 class="item-title">{{ item.name }}</h3>
          <div class="item-classify">
            {{ classifyStore.classifies.find((c) => c.id === item.classifyId)?.name || '未分类' }}
          </div>
          <div class="item-tags">
            <el-tag v-for="tag in item.tags" :key="tag" size="small" class="tag">
              {{ tag }}
            </el-tag>
          </div>
          <div class="item-actions">
            <el-button icon="Share" @click.stop="onShare(item.url)" circle />
            <el-button icon="Search" @click.stop="onPreview(item.id)" circle />
            <el-button icon="Edit" @click.stop="onEdit(item)" circle />
            <el-button icon="Delete" @click.stop="onDelete(item)" circle />
            <!-- 创作图片 -->
            <el-button icon="Picture" @click.stop="goToCreation(item.id)" circle />
          </div>
        </div>
      </div>

      <div class="pagination">
        <el-pagination
          background
          :total="total"
          :page-size="searchForm.pageSize"
          :current-page="searchForm.pageNum"
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑图片" width="400px">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="简介">
          <el-input v-model="editForm.introduction" type="textarea" />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="editForm.classifyId" placeholder="请选择分类">
            <el-option
              v-for="item in classifyStore.classifies"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-select
            v-model="editForm.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请输入标签"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onEditSave">保存</el-button>
      </template>
    </el-dialog>

    <!-- 分享图片的对话框 -->
    <el-dialog
      title="分享图片"
      v-model="shareDialogVisible"
      @close="shareClose"
      @open="generateQRCode"
    >
      <h4 class="text-center">复制分享链接</h4>
      <span class="share-link" @click="copyShareLink">{{ shareImage }}</span>
      <h4 class="text-center">扫码查看</h4>
      <canvas ref="shareCanvas"></canvas>
    </el-dialog>

    <!-- 批量修改图片对话框 -->
    <el-dialog title="批量修改图片" v-model="batchDialogVisible" @close="batchClose">
      <!-- 分类，标签，命名规则 -->
      <el-form :model="batchForm" label-width="80px">
        <el-form-item label="分类">
          <el-select v-model="batchForm.classifyId" placeholder="请选择分类">
            <el-option
              v-for="item in classifyStore.classifies"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-select
            v-model="batchForm.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请输入标签"
          />
        </el-form-item>
        <el-form-item label="命名规则">
          <el-input
            v-model="batchForm.nameRule"
            placeholder="请输入命名规则，输入（序号）可动态生成"
          />
        </el-form-item>
        <!-- 提交 -->
        <el-form-item>
          <el-button type="primary" @click="batchSubmit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 图片裁剪编辑框 -->
    <el-dialog title="图片裁剪" v-model="cropDialogVisible" width="500px" @close="closeCropDialog">
      <ImageCropper
        :imageUrl="imageUrl"
        :picture="copperPicture"
        :space-id="spaceId"
        @crop-success="handleCropSuccess"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getPictureListAPI,
  updatePictureAPI,
  deletePictureAPI,
  batchUpdatePictureClassifyAPI,
} from '@/api/pictureAPI'
import { useClassifyStore } from '@/stores/classify'
import { useUserStore } from '@/stores/user'
import { listSpaceByUserIdAPI } from '@/api/spaceAPI'
import dayjs from 'dayjs'
import QRCode from 'qrcode'
import ImageCropper from '@/components/ImageCropper.vue'

const router = useRouter()
const classifyStore = useClassifyStore()
const userStore = useUserStore()

const userId = userStore.userInfo.id
const spaceId = ref(null)
const spaceName = ref('')

const shareImage = ref('')
const shareDialogVisible = ref(false)
const shareCanvas = ref(null)

const onShare = async (url) => {
  shareImage.value = url
  shareDialogVisible.value = true
}

const batchDialogVisible = ref(false)
const batchForm = reactive({
  spaceId: null,
  pictureIdList: [],
  classifyId: null,
  tags: [],
  nameRule: '',
})

const batchClose = () => {
  Object.assign(batchForm, {
    spaceId: null,
    pictureIdList: [],
    classifyId: null,
    tags: [],
    nameRule: '',
  })
}

// 裁剪
const imageUrl = ref('')
const cropDialogVisible = ref(false)
const copperPicture = ref(null)
const goToCrop = (picture) => {
  imageUrl.value = picture.url
  copperPicture.value = picture
  console.log('goToCrop', picture)
  cropDialogVisible.value = true
}

const closeCropDialog = () => {
  cropDialogVisible.value = false
  copperPicture.value = null
}

const handleCropSuccess = async () => {
  cropDialogVisible.value = false
  ElMessage.success('编辑成功')
  getPictureList()
}
const goToBatchEdit = () => {
  batchForm.spaceId = spaceId.value
  batchForm.pictureIdList = pictures.value.map((item) => item.id)
  batchDialogVisible.value = true
}

const batchSubmit = async () => {
  console.log('批量修改：', batchForm)

  await batchUpdatePictureClassifyAPI(batchForm)
  ElMessage.success('批量修改成功')
  batchDialogVisible.value = false
  getPictureList()
  Object.assign(batchForm, {
    spaceId: null,
    pictureIdList: [],
    classifyId: null,
    tags: [],
    nameRule: '',
  })
}

const generateQRCode = async () => {
  if (!shareCanvas.value) return
  try {
    QRCode.toCanvas(shareCanvas.value, shareImage.value, {
      width: 200,
      height: 200,
      margin: 2,
      color: {
        dark: '#333333',
        light: '#ffffff',
      },
    })
  } catch (err) {
    console.error('生成二维码失败：', err)
    ElMessage.error('生成二维码失败')
  }
}

const shareClose = () => {
  shareImage.value = ''
  shareDialogVisible.value = false
}

const copyShareLink = async () => {
  await navigator.clipboard.writeText(shareImage.value)
  ElMessage.success('复制成功')
}

// 根据分类id获取空间列表
const listSpaceByUserId = async () => {
  const { data: res } = await listSpaceByUserIdAPI()
  if (res.length === 0) {
    ElMessage.warning('您还没有创建空间哦, 请先创建一个空间吧~')
    router.push('/space')
  }
  spaceId.value = res[0].id
  spaceName.value = res[0].spaceName
}

const pictures = ref([])
const searchForm = reactive({
  searchQuery: '',
  classifyId: null,
  pageNum: 1,
  pageSize: 10,
  date: [],
})

const total = ref(0)

const getPictureList = async () => {
  const startEditTime = searchForm.date[0]
    ? dayjs(searchForm.date[0]).format('YYYY/MM/DD HH:mm:ss')
    : null
  const endEditTime = searchForm.date[1]
    ? dayjs(searchForm.date[1]).format('YYYY/MM/DD HH:mm:ss')
    : null
  const res = await getPictureListAPI({
    ...searchForm,
    spaceId: spaceId.value,
    startEditTime,
    endEditTime,
  })

  if (res.code === 200) {
    pictures.value = res.data.records
    total.value = res.data.total
  } else {
    ElMessage.error('获取图片列表失败')
  }
}

const onSearch = () => {
  searchForm.pageNum = 1
  getPictureList()
}

const onReset = () => {
  searchForm.searchQuery = ''
  searchForm.classifyId = null
  searchForm.pageNum = 1
  getPictureList()
}

const onPreview = (pictureId) => {
  console.log('pictureId', pictureId)

  router.push({
    path: '/picture_search',
    query: {
      pictureId,
    },
  })
}

// 跳转到创作图片页面
const goToCreation = (pictureId) => {
  router.push({
    path: '/picture_editor',
    query: {
      pictureId,
    },
  })
}

// 跳转到上传页面
const goToUpload = () => {
  router.push({
    path: '/upload',
    query: { spaceId: spaceId.value },
  })
}

// 编辑相关
const editDialogVisible = ref(false)
const editForm = reactive({
  id: null,
  name: '',
  introduction: '',
  classifyId: '',
  tags: [],
})

const onEdit = (row) => {
  editForm.id = row.id
  editForm.name = row.name
  editForm.introduction = row.introduction
  editForm.classifyId = row.classifyId
  editForm.tags = row.tags
  editDialogVisible.value = true
}

const onEditSave = async () => {
  await updatePictureAPI({
    id: editForm.id,
    name: editForm.name,
    introduction: editForm.introduction,
    classifyId: editForm.classifyId,
    tags: editForm.tags,
    userId: userId,
  })

  ElMessage.success('编辑成功')
  getPictureList()
  editDialogVisible.value = false
}

// 删除
const onDelete = (row) => {
  ElMessageBox.confirm('确定要删除该图片吗？', '提示', {
    type: 'warning',
  })
    .then(async () => {
      await deletePictureAPI({ id: row.id })
      getPictureList()
      ElMessage.success('删除成功')
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 新增分页事件处理函数
const handleCurrentChange = (val) => {
  searchForm.pageNum = val
  getPictureList()
}

const handleSizeChange = (val) => {
  searchForm.pageSize = val
  searchForm.pageNum = 1
  getPictureList()
}

onMounted(() => {
  listSpaceByUserId().then(() => {
    getPictureList()
  })

  classifyStore.fetchClassifies()
})
</script>

<style scoped>
.space-detail {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}
.search-card {
  margin-bottom: 18px;
}
.table-card {
  margin-top: 0;
}
.tag {
  margin-right: 4px;
}
.pagination {
  margin-top: 20px;
  justify-content: center;
}

/* 新增网格布局样式 */
.gallery-section {
  margin-top: 40px;
}

.gallery-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 30px;
}

.gallery-item {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition:
    transform 0.3s,
    box-shadow 0.3s;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.gallery-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.image-container {
  height: 200px;
  overflow: hidden;
}

.gallery-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s;
}

.gallery-item:hover .gallery-image {
  transform: scale(1.05);
}

.item-title {
  font-size: 16px;
  font-weight: 500;
  margin: 12px 12px 8px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.item-classify {
  font-size: 14px;
  color: #666;
  margin: 0 12px 8px;
}

.item-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin: 0 12px 12px;
}

.tag {
  font-size: 12px;
}

.item-stats {
  display: flex;
  justify-content: space-between;
  padding: 0 12px;
  margin-bottom: 12px;
}

.stat {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #666;
}

.item-actions {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  padding: 8px 10px;
  background-color: #f9f9f9;
  border-top: 1px solid #eee;
  gap: 8px;
}

.pagination {
  margin-top: 40px;
  display: flex;
  justify-content: center;
}
.text-center {
  margin-bottom: 5px;
}
.share-link {
  font-size: 12px;
  color: #888;
  word-break: break-all;
  margin-top: 4px;
  text-align: center;
  cursor: pointer;
}
.share-link:hover {
  color: #5ab7e2;
}
</style>
